import { NetApi } from '../../../utils/net'

// ------------------------------------
// Constants
// ------------------------------------
const LOGIN_INIT = 'LOGIN_INIT'
const LOGIN_ING = 'LOGIN_ING'
const LOGIN_FAIL = 'LOGIN_FAIL'
const LOGIN_SUC = 'LOGIN_SUC'

// ------------------------------------
// Actions
// ------------------------------------
const login = () => {
  return {
    type: LOGIN_ING
  }
}

const loginInit = () => {
  return {
    type: LOGIN_INIT
  }
}

const loginFail = (err) => {
  return {
    type: LOGIN_FAIL,
    payload: err
  }
}

const loginSuc = (data) => {
  return {
    type: LOGIN_SUC,
    payload: data
  }
}

const fetchLogin = () => {
  return (dispatch, getState) => {
    if (getState().layoutState.fetching) {
      return
    }

    dispatch(login())

    // 获取参数
    let qp = {
      type: 1,
      clientType: getState().params.isMobile ? 1 : 0
    }
    let url = NetApi.buildQueryUrl('/api/login', qp)
    NetApi.get(url, (err, json) => {
      if (err) {
        dispatch(loginFail(err))
      } else {
        if (json.success) {
          dispatch(loginSuc(json.data))
        } else {
          dispatch(loginFail(json.message))
        }
      }
    })
  }
}

export const actions = {
  loginInit,
  login,
  loginFail,
  loginSuc,
  fetchLogin
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [LOGIN_INIT] : (state) => ({ ...state, fetching: false, err: null, data: {} }),
  [LOGIN_ING] : (state) => ({ ...state, fetching: true, err: null, data: {} }),
  [LOGIN_FAIL]    : (state, action) => ({ ...state, fetching: false, err: action.payload, data: {} }),
  [LOGIN_SUC] : (state, action) => ({ ...state, fetching: false, err: null, data: action.payload }),
}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
  fetching: false,
  data: {}
}
export default function (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]
  return handler ? handler(state, action) : state
}
